import { baseConfig } from "../config/baseConfig";
import { isAuthPass } from "@/utils/authentication.js";

function baseRequest({ method, url, data, headers, timeout }) {
  let requestUrl = url.includes("http") ? url : baseConfig.baseUrl + url;
  return new Promise((resolve, reject) => {
    if (isAuthPass()) return resolve({});
    uni.request({
      url: requestUrl,
      method: method || "GET",
      header: {
        ...headers,
      },
      timeout,
      data: data || {},
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data);
          } else {
            uni.showToast({
              title: "参数错误",
              icon: "error",
              duration: 2000,
            });
            resolve({});
          }
        } else {
          // uni.showToast({
          //   title: "服务端异常",
          //   icon: "error",
          //   duration: 2000,
          // });
          resolve({});
        }
      },
      fail: (err) => {
        resolve({});
      },
    });
  });
}

const request = {};

const methodList = ["options", "get", "post", "put", "head", "delete", "trace", "connect"];

methodList.forEach((method) => {
  request[method] = ({ url, data, headers, timeout = 20000 }) => {
    return baseRequest({ method, url, data, headers, timeout });
  };
});

export default request;
